package com.bbs.toutiao.controller.admin;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.bbs.toutiao.entity.UserEntity;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import com.bbs.toutiao.service.admin.impl.UploadServiceImpl;
import com.bbs.toutiao.utils.MsgCodeUtil;
import com.bbs.toutiao.utils.Result;
import com.bbs.toutiao.service.admin.impl.UserEditorImpl;
import com.bbs.toutiao.vo.comm.PageVo;
import com.bbs.toutiao.vo.user.UpdateStatusVo;
import com.bbs.toutiao.vo.user.UserRequestPageVo;
import com.bbs.toutiao.vo.user.UserResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 描述:用户编辑，查询
 * 作者： zhangBin
 * 时间： 2023/9/19 14:10
 * 版本： 1.0
 */

@Slf4j
@RestController
@RequestMapping("/user")
public class UserEditorController {

    @Resource
    UserEditorImpl userEditor;

    @Resource
    UploadServiceImpl uploadService;

    /**
     * 根据id获取用户信息
     *
     * @param token
     * @return
     */
    @GetMapping("/getUserData")
    public Result getUserData(@RequestHeader String token) {
        try {
            JWT jwt = JWTUtil.parseToken(token);
            Integer id = Integer.parseInt(jwt.getPayload("userId").toString());
            UserEntity user = userEditor.getUserData(id);
            user.setPassword(" ");
            return Result.success("获取成功", user);
        } catch (Exception e) {
            throw new BaseException(ExceptionEnum.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 修改用户状态
     *
     * @param statusVo
     * @return
     */
    @PostMapping("/updateStatus")
    public Result updateStatus(@RequestBody UpdateStatusVo statusVo, @RequestHeader String token) {
        try {
            Assert.notNull(statusVo);
        } catch (IllegalArgumentException e) {
            throw new BaseException(ExceptionEnum.NOT_NULL);
        }

        JWT jwt = JWTUtil.parseToken(token);
        String userId = jwt.getPayload("userId").toString();
        if (Integer.parseInt(userId) == statusVo.getId()) {
            return Result.error(300,"不能修改自己的状态");
        }

        if (userEditor.updateStatus(statusVo)) {
            return Result.success("修改成功");
        }
        return Result.error(401, "修改失败");
    }

    /**
     * 动态查询用户
     *
     * @param searchVo
     * @return Result
     */
    @PostMapping("/findByUserPage")
    public Result findByUserSearch(@RequestBody UserRequestPageVo searchVo) {
        if (searchVo.getPage() < 1 || searchVo.getSize() < 1) {
            return Result.error(401, "请求的数据格式错误");
        }
        searchVo.setPage(searchVo.getPage(), searchVo.getSize());
        PageVo<UserResponseVo> userList = userEditor.userSearchPage(searchVo);
        return Result.success("查询成功", userList);
    }


    /**
     * 允许行阿里云上传，发送key和id
     *
     * @param token
     * @return
     */
    @GetMapping("/upload")
    public Result upload() {
        Map<String, String> stringMap = uploadService.upload();
        return Result.success("允许上传", stringMap);
    }

    /**
     * 动态更新用户
     *
     * @param user
     * @return
     */
    @PostMapping("/updateUserById")
    public Result updateUserById(@RequestBody UserEntity user, @RequestHeader String token) {
        int i = userEditor.updateUserInfoById(user, token);
        if (i > 0) {
            return Result.success("更新成功");
        } else {
            return Result.error(401, "更新失败");
        }
    }

    /**
     * 动态更新密码和邮箱
     *
     * @param user
     * @param token
     * @return
     */
    @PostMapping("/updateUserPasswordById")
    public Result deleteUserById(@RequestBody UserEntity user, @RequestHeader String token) {
        MsgCodeUtil.startCleanerCache();//开启定时清理
        if (!MsgCodeUtil.booleanCode(user.getUserEmail(), user.getCaptcha())) {
            return Result.error(401, "验证码过期");
        }
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            String password = MD5.create().digestHex(user.getPassword(), StandardCharsets.UTF_8);
            user.setPassword(password);
        }
        int i = userEditor.updateUserInfoById(user, token);
        if (i > 0) {
            return Result.success("更新成功");
        } else {
            return Result.error(401, "更新失败");
        }
    }
}
